#include <string.h>
#include <iostream>
using std::cout;
using std::endl;
//析构函数设置为虚函数
//Base:  Derived:  各自数据成员申请堆空间
class Base{
public:
    Base(const char * base)
    :_base(new char[strlen(base) + 1]())
    {
        strcpy(_base, base);
        cout << "Base(const char *)" << endl;
    }
    //析构函数
    virtual
    ~Base(){
        cout << "~Base()" << endl;
        if(_base){
            delete [] _base;
            _base = nullptr;
        }
    }

    virtual void print(){
        cout << "Base::print()" << endl;
    }

private:
    char * _base;
};

class Derived : public Base{
public:
    Derived(const char * base,const char * derived)
    :Base(base)
    ,_derived(new char[strlen(derived) + 1]())
    {
        cout << "Derived(const char *)" << endl;
        strcpy(_derived, derived);
    }
    
    ~Derived(){
        cout << "~Derived()" << endl;
        if(_derived){
            delete [] _derived;
            _derived = nullptr;
        }
    }
    virtual void print() override{
        cout << "Derived::print()" << endl;
    }


private:
    char * _derived;
};

void test(){
    //Derived d("hello", "world");
    Derived d("hello", "world");
    Base * pbase = &d;
    pbase->print();

}

void test2(){
    //上述的代码是没有任何问题的
    //，但是如果基类的指针指向的是位于堆区的派生类对象呢？
    Base * pbase2 = new Derived("hell0", "world");
    pbase2->print();
    delete pbase2;
}

int main()
{
    test2();
    return 0;
}

